<!-- 个人中心页面 -->
<template>
  <div class="personal">
    <!-- 左侧导航 -->
    <div class="personal-left">
      <el-menu
        :default-active="activeIndex"
        class="person-menu"
        @select="handleSelect"
      >
        <el-menu-item index="1">
          <i class="el-icon-user"></i>
          <span>基本信息</span>
        </el-menu-item>
        <el-menu-item index="2">
          <i class="el-icon-location"></i>
          <span>收货地址</span>
        </el-menu-item>
        <el-menu-item index="3">
          <i class="el-icon-star-on"></i>
          <span>我的评价</span>
        </el-menu-item>
      </el-menu>
    </div>
    <!-- 左侧导航END -->

    <!-- 右侧内容区 -->
    <div class="personal-right">
      <!-- 基本信息部分 -->
      <div v-show="activeIndex === '1'" class="info-container">
        <h3>基本信息</h3>
        <el-form :model="userInfo" label-width="80px">
          <!-- 头像上传 -->
          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              action=""
            >
              <img
                v-if="userInfo.user_avatar"
                :src="userInfo.user_avatar"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <!-- 用户名 -->
          <el-form-item label="用户名">
            <el-input v-model="userInfo.user_name" disabled></el-input>
          </el-form-item>
          <!-- 手机号 -->
          <el-form-item label="手机号">
            <el-input v-model="userInfo.user_phonenumber"></el-input>
          </el-form-item>
          <!-- 性别 -->
          <el-form-item label="性别">
            <el-radio-group v-model="userInfo.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 保存按钮 -->
          <el-form-item>
            <el-button type="primary" @click="saveUserInfo">保存修改</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 基本信息部分END -->

      <!-- 收货地址部分 -->
      <div v-show="activeIndex === '2'" class="address-container">
        <h3>收货地址</h3>
        <!-- 添加地址按钮 -->
        <el-button type="primary" @click="showAddressDialog"
          >添加地址</el-button
        >

        <!-- 地址列表 -->
        <div class="address-list">
          <el-card
            v-for="addr in addressList"
            :key="addr.id"
            class="address-item"
          >
            <div class="address-info">
              <p><span class="label">收货人：</span>{{ addr.linkman }}</p>
              <p><span class="label">手机号：</span>{{ addr.phone }}</p>
              <p><span class="label">地址：</span>{{ addr.address }}</p>
            </div>
            <div class="address-actions">
              <el-button type="text" @click="editAddress(addr)">编辑</el-button>
              <el-button type="text" @click="deleteAddress(addr.id)"
                >删除</el-button
              >
            </div>
          </el-card>
        </div>

        <!-- 地址编辑对话框 -->
        <!-- 使用MyAddress组件 -->
        <!-- 让父组件 (Personal.vue) 完全控制地址的新增/编辑操作 -->
        <MyAddress
          :visible.sync="dialogVisible"
          :edit-address="addressForm"
          :isEdit="isEdit"
          :title="dialogTitle"
          @refresh="getAddressList"
        ></MyAddress>
      </div>
      <!-- 收货地址部分END -->
    </div>
    <!-- 右侧内容区END -->
  </div>
</template>
<script>
import MyAddress from "../components/MyAddress.vue";

export default {
  name: "Personal",
  components: {
    MyAddress, // 注册组件
  },
  data() {
    return {
      activeIndex: "1", // 当前选中的菜单项
      // 用户信息
      userInfo: {
        user_id: "",
        user_name: "",
        user_phonenumber: "",
        user_avatar: "",
        gender: 0, // 性别（0=未知，1=男，2=女）
      },
      avatarFile: null, // 🌟临时存头像文件
      // 地址列表
      addressList: [],
      // 地址表单
      addressForm: {
        id: "",
        linkman: "",
        phone: "",
        address: "",
        user_id: "",
      },
      dialogVisible: false, // 控制对话框显示
      dialogTitle: "", // 对话框标题
      isEdit: false, // 是否是编辑模式
    };
  },
  created() {
    // 获取用户信息
    this.initUserInfo();
    // 获取地址列表
    this.getAddressList();
  },
  methods: {
    // 初始化用户信息
    initUserInfo() {
      const user = this.$store.getters.getUser;
      if (user) {
        this.$axios
          .post("api/user/info", {
            user_id: user.user_id,
          })
          .then((res) => {
            if (res.data.code === "001") {
              // 正确访问 res.data.data 中的字段
              const userData = res.data.data;
              this.userInfo = {
                user_id: userData.user_id,
                user_name: userData.userName,
                user_phonenumber: userData.userPhonenumber,
                user_avatar: userData.userAvatar,
                gender: userData.gender,
              };
            }
          })
          .catch((err) => {
            console.error("获取用户信息失败:", err);
          });
      }
    },
    // 切换菜单
    handleSelect(index) {
      this.activeIndex = index;
      if (index === "1") {
        this.initUserInfo(); // 每次切到基本信息都刷新用户信息
      } else if (index === "3") {
        // 跳转到我的评价页面
        this.$router.push("/comment");
      }
    },
    // 保存用户信息
    async saveUserInfo() {
      // async是为了能用await
      try {
        // 1.判断是否需要上传头像
        if (this.avatarFile) {
          const formData = new FormData();
          formData.append("file", this.avatarFile);
          formData.append("user_id", this.userInfo.user_id);

          // await:等这个异步操作执行完再往下走
          const res = await this.$axios.post(
            "/api/user/uploadAvatar",
            formData,
            {
              headers: { "Content-Type": "multipart/form-data" },
            }
          );

          if (res.data.code === "001") {
            this.userInfo.user_avatar = res.data.data; // 设置为服务器图片地址
            this.avatarFile = null; // 清除临时文件
          } else {
            this.$message.error(res.data.msg);
            return;
          }
        }

        // 2.保存用户信息
        const updateRes = await this.$axios.post(
          "/api/user/update",
          this.userInfo
        );

        if (updateRes.data.code === "001") {
          this.$message.success(updateRes.data.msg);
        } else {
          this.$message.error(updateRes.data.msg);
        }
      } catch (err) {
        console.error(err);
        this.$message.error("saveUserInfo()请求失败！");
      }
    },
    // 头像上传前回调
    beforeAvatarUpload(file) {
      this.avatarFile = file; // 保存原始文件等下上传
      // 创建预览 URL
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        this.userInfo.user_avatar = reader.result; // 设置为 base64 临时预览
      };

      // 暂时不上传，返回 false
      return false;
    },
    // 获取地址列表
    getAddressList() {
      const user = JSON.parse(localStorage.getItem("user"));
      if (user) {
        this.$axios
          .post("api/user/address/list", {
            user_id: this.$store.getters.getUser.user_id,
          })
          .then((res) => {
            if (res.data.code === "001") {
              this.addressList = res.data.data;
            }
          })
          .catch((err) => {
            return Promise.reject(err);
          });
      }
    },
    // 新增地址数据准备
    showAddressDialog() {
      this.dialogTitle = "新增地址";
      this.isEdit = false; // 设置为新增
      this.addressForm = {
        // 清空
        id: "",
        linkman: "",
        phone: "",
        address: "",
        user_id: JSON.parse(localStorage.getItem("user")).user_id,
      };

      this.dialogVisible = true;
    },
    // 编辑地址数据准备
    editAddress(addr) {
      this.addressForm = { ...addr };
      this.isEdit = true; // 设置为编辑
      this.dialogVisible = true;
      this.dialogTitle = "编辑地址";
    },

    // 删除地址
    deleteAddress(id) {
      this.$confirm("确定要删除该地址吗？", "提示", {
        type: "warning",
      }).then(() => {
        this.$axios
          .post("/api/user/address/remove", {
            id: id,
          })
          .then((res) => {
            if (res.data.code === "001") {
              this.$message.success("删除成功");
              this.getAddressList();
            } else {
              this.$message.error("删除失败");
            }
          });
      });
    },
  },
};
</script>

<style scoped>
.personal {
  max-width: 1225px;
  margin: 0 auto;
  padding: 20px;
  display: flex;
  gap: 20px;
}

/* 左侧导航样式 */
.personal-left {
  width: 200px;
}

.personal-menu {
  border-right: none;
}

/* 右侧内容区样式 */
.personal-right {
  flex: 1;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

/* 头像上传样式 */
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  width: 100px;
  height: 100px;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

/* 地址列表样式 */
.address-list {
  margin-top: 20px;
}

.address-item {
  margin-bottom: 15px;
}

.address-info {
  line-height: 1.8;
}

.address-actions {
  margin-top: 10px;
  text-align: right;
}

.label {
  color: #666;
  margin-right: 10px;
}
</style>